package com.atguigu.gmall.realtime.app;

import com.atguigu.gmall.realtime.util.FlinkSourceUtil;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/10/26 10:14
 */
public abstract class BaseAppV2 {
    public abstract void run(StreamExecutionEnvironment env,
                             HashMap<String, DataStreamSource<String>> topicAndStreamMap);
    
    public void init(int port, int p, String ck, String groupId, String topic, String... otherTopics) {
        System.setProperty("HADOOP_USER_NAME", "atguigu");
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", port);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(p);
        
        env.enableCheckpointing(3000, CheckpointingMode.EXACTLY_ONCE);
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop162:8020/gmall/" + ck);
        
        env.getCheckpointConfig().setCheckpointTimeout(10 * 1000);
        env
            .getCheckpointConfig()
            .enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
        
        ArrayList<String> topics = new ArrayList<>();
        topics.add(topic);
        topics.addAll(Arrays.asList(otherTopics));
    
        HashMap<String, DataStreamSource<String>> topicAndStreamMap = new HashMap<>();
        for (String t : topics) {
            
            DataStreamSource<String> stream = env.addSource(FlinkSourceUtil.getKafkaSource(groupId, t));
            topicAndStreamMap.put(t, stream);
        }
        
        // 不同的app有不同 的业务逻辑
        run(env, topicAndStreamMap);
        try {
            env.execute(ck);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
